package com.roc.web.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.TermBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Esmidinfo;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.TPosInfo;
import com.roc.pojo.TblDictionaryItem;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblTermInf;
import com.roc.pojo.TermInfo;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.ConfigPropertiesUtils;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.Terminal;
import com.roc.util.constant.TerminalBrand;
import com.roc.util.constant.TerminalFlag;
import com.roc.util.constant.TerminalName;
import com.roc.util.constant.TerminalType;
@Component
@Scope("prototype")
@Namespace("/terminal")
public class TerminalQueryAction extends PaginationBaseAction{

	private Logger logger=LogManager.getLogger(OperatorQueryAction.class);
	private TerminalSearchCondition searchCondition;
	
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	
	private List<TermBean> terminalList=new ArrayList<TermBean>();
	
	private Esmidinfo esmidinfo;
	
	private TblMchtInf tblMchtInf;
	
	private TPosInfo yjPos;
	
	private TermInfo termInfo;
	
	private TblTermInf termInfos=new TblTermInf();
	
	private String mid;
	
	private String tid;
	
	private String nowserialNum;
	
	private String posBrandCode;// 厂商编号
	
	private String dealFlag;// 1解绑 2重绑
	
	private String serialNum3;//重绑的终端序列号

	private InputStream excelFile;
	
	private String  excelName;
	
	@Autowired
	IorgService orgService;
	@Autowired
	ITerminalService terminalService;
	@Autowired
	IPageService pagenitionService;
	@Autowired 
	IMerchantServices merchantServices;
	@Autowired
	IPowerInfoService powerInfoService;
	@Autowired
	IExcelService excelService;
	
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/terminal/terminal_query.jsp")
    })
	public String init() throws Exception{
		org();
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		searchCondition=new TerminalSearchCondition();		
		if(Role.MERCHANT.getCode().equals(logingMerchant.getRoleType())){			
			searchCondition.setMid(logingMerchant.getAccountNo());
			searchCondition.setMidName(logingMerchant.getRealName());
		}   
	   return SUCCESS;
    }
	
	@Action(value = "terminalQuery", 
			results = { @Result(name = "success", location = "/pages/terminal/terminal_query.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String terminalQuery() throws Exception{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(searchCondition==null){
			searchCondition=(TerminalSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new TerminalSearchCondition();
			}
		}
		
		try {
			org();			
			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
	        String superRole= map.get("superRole");
	        String opRealId =map.get("opRealId");
	        searchCondition.setGroupCd(map.get("groupCd"));
	        searchCondition.setRoleType(superRole);// 角色
	        searchCondition.setOpId(opRealId);//当前人员id
	        searchCondition.setOneOrgCode(op.getOneagentid());//机构
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);
			}

			String isShowExp = "0";
	        // 非系统管理员/机构管理员/系统运营，不允许显示导出按钮
			if( op.getRoleType().equals(Role.SYSTEM.getCode())
					|| ( op.getRoleType().equals(Role.O_MANAGER.getCode())  )
					|| ( superRole.equals(Role.SYSTEM.getCode()) && op.getRoleType().equals(Role.OPERATORS_COMM.getCode()) ) ) {
				isShowExp = "1";
			}
			getRequest().setAttribute("isShowExp", isShowExp);
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (Exception e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
		
	}

	@Action(value="excelTerminalQuery",results = {@Result(name="success",type="stream"
	,params = { "contentType", "application/vnd.ms-excel", "inputName",  
	            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
"bufferSize", "1024*3" }),@Result(name="error",location="/pages/terminal/terminal_query.jsp") }) 
	public String excelTerminalQuery() throws Exception{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		String reportName = "终端信息导出";

		try {
			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
	        String superRole= map.get("superRole");
	        String opRealId =map.get("opRealId");
	        
	        // 非系统管理员/机构管理员/系统运营，不允许显示导出按钮
			if( !op.getRoleType().equals(Role.SYSTEM.getCode())
					&& !( op.getRoleType().equals(Role.O_MANAGER.getCode())  )
					&& !( superRole.equals(Role.SYSTEM.getCode()) && op.getRoleType().equals(Role.OPERATORS_COMM.getCode()) ) ) {
				addActionError("此登陆账号没有权限");
				return ERROR;
				
			}
			org();			
	        searchCondition.setGroupCd(map.get("groupCd"));
	        searchCondition.setRoleType(superRole);// 角色
	        searchCondition.setOpId(opRealId);//当前人员id
	        searchCondition.setOneOrgCode(op.getOneagentid());//机构
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
				dealWithTheListSpecially(searchRsList);
			}

			setExcelName(new String(reportName.getBytes(), "ISO8859-1"));
			
			HSSFWorkbook work = excelService.excelTerminalQuery(terminalList);
			ByteArrayOutputStream output = new ByteArrayOutputStream();  
			work.write(output);  
			   
			byte[] ba = output.toByteArray();  
			excelFile = new ByteArrayInputStream(ba);  
			output.flush();  
			output.close(); 
			
		} catch (Exception e) {
			logger.info("######导出" + reportName + "失败######");
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
		
	}
	protected void dealWithTheListSpecially(List<Object> list){
		
		if(list!=null&&list.size()>0){
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				TermBean temp=new TermBean();
				Object[] obj=(Object[]) iterator.next();
				temp.setMid(Constance.Null2EmptyTrim(obj[0]));
				temp.setMerName(Constance.Null2EmptyTrim(obj[1]));
				for(TblInsInf bean:orgList){
					if(Constance.Null2EmptyTrim(obj[2]).equals(bean.getInsIdCd())){
						temp.setOrgName(bean.getInsName());
					}
				}
				temp.setTid(Constance.Null2EmptyTrim(obj[3]));
				temp.setTermName(Constance.Null2EmptyTrim(obj[4]));
				temp.setTermAddress(Constance.Null2EmptyTrim(obj[5]));
				//temp.setTidKind(Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[6])).getName());
				//TblDictionaryItem tdItem=new TblDictionaryItem();
				/*tdItem.getId().setDicCode(Constance.Null2EmptyTrim(obj[6]));
				try {
					tdItem=terminalService.queryDictionaryItemByTypeStatus(tdItem);
				} catch (ServiceException e) {
					logger.info("查询终端类型出错!!!");
					e.printStackTrace();
				}*/
				temp.setTidKind(ConfigMerinfoUtil.getPosType(Constance.Null2EmptyTrim(obj[6])));
				temp.setFlag(TerminalFlag.valueOfCode(Constance.Null2EmptyTrim(obj[7])).getName());				
				temp.setSerialNum(Constance.Null2EmptyTrim(obj[8]));
				temp.setAgentName(Constance.Null2EmptyTrim(obj[9]));
				//temp.setInstallStatus(Constance.Null2EmptyTrim(obj[9]));
				//temp.setInstallStatusName(Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[9])).getName());
               /* temp.setAgentName(Constance.Null2EmptyTrim(obj[10]));
                temp.setAgentId(new Long(Constance.Null2EmptyTrim(obj[11])));
                temp.setMobile(Constance.Null2EmptyTrim(obj[12]));
                temp.setCardNo(Constance.Null2EmptyTrim(obj[13]));*/
                
				terminalList.add(temp);
			}
		}

	}
	
	//查询机构
	public void org() throws Exception{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		/*if(Role.SYSTEM.getCode().equals(logingMerchant.getRoleType())){
			TblInsInf inf = new TblInsInf();
			inf.setInsIdCd("");
			inf.setInsName("--请选择机构--");
			orgList.add(inf);
			List<TblInsInf> list=orgService.queryOrgList();
			orgList.addAll(list);
		}else{
			TblInsInf infs=orgService.queryOrgByOrgCode(logingMerchant.getOrgCode());
			orgList.add(infs);
		}*/
		TblInsInf infs=orgService.queryOrgByOrgCode(logingMerchant.getOrgCode());
		orgList.add(infs);
	}
	
	//解绑页面初始化
	@Action(value = "terminalSnUnbundInit", results = { @Result(name = "success", location = "/pages/terminal/terminal_sn_unbund_pay.jsp")
    })
	public String terminalSnUnbundInit() throws Exception{
		try {
			tblMchtInf=merchantServices.queryMerchat(mid);
			termInfos=terminalService.queryTermInfopart(tid,mid);
			yjPos=terminalService.queryYsbYjPosInfo(termInfos.getDeviceCd(),termInfos.getTmnlBrand());
			if(yjPos!=null){
				//yjPos.setPosBrand(TerminalBrand.valueOfCode(yjPos.getPosBrand()).getName());
				//yjPos.setPosType(TerminalType.valueOfCode(yjPos.getPosType()).getName());
				yjPos.setPosBrandCode(yjPos.getPosBrand());		
				yjPos.setPosName(ConfigMerinfoUtil.getPosMODEL(yjPos.getPosName(), yjPos.getPosBrand()));
				yjPos.setPosBrand(ConfigMerinfoUtil.getPosBRAND(yjPos.getPosBrand()));
				yjPos.setPosType(ConfigMerinfoUtil.getPosType(yjPos.getPosType()));				
			}
		
			getRequest().setAttribute("dealFlag", dealFlag);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
	
	    return SUCCESS;
	}
	
	/**
	 * 终端解绑
	 * @return
	 * @throws Exception
	 */
	@Action(value = "terminalSnUnbund", results = { @Result(name = "success", location = "/pages/terminal/terminal_sn_unbund_pay.jsp"),
			@Result(name="error",location="/error.jsp")
    })
	public String terminalSnUnbund() throws Exception{
		try {
		if(Constance.isEmpty(mid)||Constance.isEmpty(tid)||Constance.isEmpty(nowserialNum)||Constance.isEmpty(posBrandCode))
		{
			addActionError("传递的参数值异常,请重新登录或者刷新页面!");
			return ERROR;
		}
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		terminalService.unbindYsbTerminal(nowserialNum,posBrandCode,mid,tid,logingMerchant.getAccountNo());
		dealFlag = "3";//
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return terminalSnUnbundInit();
	}
	
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERMINAL_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BEAN_TERMINAL_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public TerminalSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(TerminalSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public List<TermBean> getTerminalList() {
		return terminalList;
	}

	public void setTerminalList(List<TermBean> terminalList) {
		this.terminalList = terminalList;
	}

	public Esmidinfo getEsmidinfo() {
		return esmidinfo;
	}

	public void setEsmidinfo(Esmidinfo esmidinfo) {
		this.esmidinfo = esmidinfo;
	}

	public TPosInfo getYjPos() {
		return yjPos;
	}

	public void setYjPos(TPosInfo yjPos) {
		this.yjPos = yjPos;
	}

	public TermInfo getTermInfo() {
		return termInfo;
	}

	public void setTermInfo(TermInfo termInfo) {
		this.termInfo = termInfo;
	}

	public String getMid() {
		return mid;
	}

	public void setMid(String mid) {
		this.mid = mid;
	}

	public String getTid() {
		return tid;
	}

	public void setTid(String tid) {
		this.tid = tid;
	}

	public String getDealFlag() {
		return dealFlag;
	}

	public void setDealFlag(String dealFlag) {
		this.dealFlag = dealFlag;
	}

	public String getSerialNum3() {
		return serialNum3;
	}

	public void setSerialNum3(String serialNum3) {
		this.serialNum3 = serialNum3;
	}

	public TblTermInf getTermInfos() {
		return termInfos;
	}

	public void setTermInfos(TblTermInf termInfos) {
		this.termInfos = termInfos;
	}

	public TblMchtInf getTblMchtInf() {
		return tblMchtInf;
	}

	public void setTblMchtInf(TblMchtInf tblMchtInf) {
		this.tblMchtInf = tblMchtInf;
	}

	public String getNowserialNum() {
		return nowserialNum;
	}

	public void setNowserialNum(String nowserialNum) {
		this.nowserialNum = nowserialNum;
	}

	public String getPosBrandCode() {
		return posBrandCode;
	}

	public void setPosBrandCode(String posBrandCode) {
		this.posBrandCode = posBrandCode;
	}
	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}  

	
}
